#!/bin/bash

# Copyright (c) KylinSoft Co., Ltd. 2016-2024.All rights reserved.
## kylin-kmre-make-image is licensed under the Apache License, Version 2.0.
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##         http://www.apache.org/licenses/LICENSE-2.0
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.

PRINT_LEVEL_ERROR=3     # 错误信息
PRINT_LEVEL_WARN=4      # 警告信息
PRINT_LEVEL_NOTICE=5    # 提示信息
PRINT_LEVEL_INFO=6      # 运行时信息
PRINT_LEVEL_DEBUG=7

ANDROID_IMAGE=system.sfs
DOCKER_IMAGE_NAME=kmre3
DOCKER_IMAGE_VERSION=v3.0-250328.14

TMPDIR="."
if [ "$IMAGE_DIR_PREFIX" != "" ]; then
    TMPDIR=$IMAGE_DIR_PREFIX
fi

ARCH=$(uname --processor)
if [ "$ARCH" == "unknown" ]; then
    ARCH="aarch64"
fi

umount ${TMPDIR}/squashfs-root 2>/dev/null
umount kmre-filesystem 2>/dev/null

script_print_debug_line()
{
    level=3
    if [ "${PRINT_LEVEL}X" != "X" ]; then
        level=${PRINT_LEVEL}
    fi

    if [ ${level} -ge 7 ]; then
        if [ "${PRINT_COLOR}X" == "1X" ]; then
            echo -e "\033[01;33m[DEBUG]" $@ "\033[0m"
        else
            echo $@
        fi
    fi
}

create_kmre_docker_file()
{
    DFPATH="kmre-filesystem"
    if [ "${1}X" != "X" ]; then
        DFPATH=$1
    fi

    DFNAME="kmre.dockfile"
    if [ "${2}X" != "X" ]; then
        DFNAME=$2
    fi

    DFFILE=`readlink -m ./${DFPATH}/${DFNAME}`
    echo "DF = " ${DFFILE}

    cat > ${DFFILE} << EOF
FROM scratch

COPY ./ /

RUN /setpermissions.sh

CMD [ "/init.kmre" ]

EOF

}

create_kmre_filesystem()
{
    FSROOT="kmre-filesystem"
    if [ "${1}X" != "X" ]; then
        FSROOT=$1
    fi

    # Create android filesystem
    rm -rf ${TMPDIR}/squashfs-root
    umount -f ${FSROOT}
    rm -rf ${FSROOT}
    mkdir ${FSROOT}
    unsquashfs -d ${TMPDIR}/squashfs-root ${ANDROID_IMAGE}
    mount ${TMPDIR}/squashfs-root/system.img ${FSROOT}
    rm ${FSROOT}/bin

    cd $FSROOT
    find . | xargs stat -c "%u:%g %n" > ../setpermissions.sh
    cd -
    sed -i '/0:0/d' setpermissions.sh
    sed -i 's/^/chown -h /g' setpermissions.sh
    sed -i '1i\#!/bin/sh' setpermissions.sh
    chmod 755 setpermissions.sh
    # Copy setpermissions.sh
    cp setpermissions.sh ${FSROOT}/

    # Create busybox filesystem
    mkdir -p ${FSROOT}/bin/

    cp busybox-${ARCH} ${FSROOT}/bin/busybox
    ${FSROOT}/bin/busybox --install -s ${FSROOT}/bin/

    # copy some libs
    #cp ${FSROOT}/system/lib64/libDisplayControlSystemCommon.so  ${FSROOT}/system/vendor/lib64
    #cp ${FSROOT}/system/lib64/lib_displayControl_enc.so  ${FSROOT}/system/vendor/lib64
    #cp ${FSROOT}/system/lib/libDisplayControlSystemCommon.so  ${FSROOT}/system/vendor/lib
    #cp ${FSROOT}/system/lib/lib_displayControl_enc.so  ${FSROOT}/system/vendor/lib

    BUSYBOX_ABSOLUTE_PATH=`readlink -m ${FSROOT}/bin/busybox`
    FILE_LIST=`ls ${FSROOT}/bin/`
    for FILE in ${FILE_LIST}
    do
        if [ -h "${FSROOT}/bin/${FILE}" ]
        then
            FILE_ABSOLUTE_PATH=`readlink -m ${FSROOT}/bin/${FILE}`
            if [ "${FILE_ABSOLUTE_PATH}X" == "${BUSYBOX_ABSOLUTE_PATH}X" ]
            then
                script_print_debug_line "Relink ${FSROOT}/bin/${FILE} to busybox"
                ln -sf busybox ${FSROOT}/bin/${FILE}
            else
                script_print_debug_line "${FSROOT}/bin/${FILE}: Not busybox link file, skip it"
            fi
        else
            script_print_debug_line "${FSROOT}/bin/${FILE}: Not a symlink file, skip it"
        fi
    done

    if [ ! -d "${FSROOT}/sockets/" ]; then mkdir -p ${FSROOT}/sockets/; fi
    cat > ${FSROOT}/system/etc/lsb-release << EOF
DISTRIB_ID=Kylin
DISTRIB_RELEASE=4.0.2
DISTRIB_CODENAME=juniper
DISTRIB_DESCRIPTION="Kylin 4.0.2"
DISTRIB_KYLIN_RELEASE=4.0-2SP2
DISTRIB_VERSION_TYPE=enterprise
DISTRIB_VERSION_MODE=normal
EOF

    rm -rf ${FSROOT}/etc
    cp -a ${FSROOT}/system/etc/ ${FSROOT}/etc

    #mv ${FSROOT}/init ${FSROOT}/init.android
    cat > ${FSROOT}/init.kmre << "EOF"
#!/bin/sh
mount -o remount,rw /sys
mount -o remount,rw /sys/firmware

#mount -o remount,rw /sys/fs/cgroup
#mount -o remount,rw /sys/fs/cgroup/systemd
#mount -o remount,rw /sys/fs/cgroup/pids
#mount -o remount,rw /sys/fs/cgroup/devices
#mount -o remount,rw /sys/fs/cgroup/freezer
#mount -o remount,rw /sys/fs/cgroup/cpu,cpuacct
#mount -o remount,rw /sys/fs/cgroup/blkio
#mount -o remount,rw /sys/fs/cgroup/cpuset
#mount -o remount,rw /sys/fs/cgroup/net_cls
#mount -o remount,rw /sys/fs/cgroup/debug
#mount -o remount,rw /sys/fs/cgroup/perf_event
#mount -o remount,rw /sys/fs/cgroup/memory

mount -o remount,rw /proc/asound
mount -o remount,rw /proc/bus
mount -o remount,rw /proc/fs
mount -o remount,rw /proc/irq
mount -o remount,rw /proc/sys
mount -o remount,rw /proc/sysrq-trigger

rm -rf /acct/*
mkdir -p /dev/input/
ln -sf /sockets/kmre_bridge /dev/kmre_bridge
ln -sf /sockets/display-control /dev/display_control
ln -sf /sockets/kmre_audio /dev/kmre_audio
ln -sf /sockets/event0 /dev/input/event100
ln -sf /sockets/event1 /dev/input/event101
ln -sf /sockets/event2 /dev/input/event102

mkdir -p /kmre
ln -sf /sockets/display-control /kmre/display_control
ln -sf /sockets/display-control /kmre/display-control

mkdir -p /desktop_switch
ln -sf /sockets/desktop-switch /desktop_switch/desktop-switch

rm -rf /dev/__properties__

netString=`ifconfig eth0 | grep "inet addr" | awk '{print $2,$4}'`
ip=`echo ${netString} | awk '{print $1}' | sed 's/addr://g'`
mask=`echo ${netString} | awk '{print $2}' | sed 's/Mask://g'`
gw=`route | grep default | awk '{print $2}'`

echo -e "IP=${ip}\nNETMASK=${mask}\nGATEWAY=${gw}" > /system/etc/kmre-network.config

exec /init >/data/kmre-init.log 2>/data/kmre-init.err

EOF
    chmod a+x ${FSROOT}/init.kmre
}

create_kmre_filesystem kmre-filesystem
create_kmre_docker_file kmre-filesystem kmre.dockerfile


docker build -t ${DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_VERSION} -f kmre-filesystem/kmre.dockerfile kmre-filesystem/
DATA_STRING=`date +%Y.%m.%d-%H.%M`
docker save ${DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_VERSION} -o ${DOCKER_IMAGE_NAME}_${DOCKER_IMAGE_VERSION}_${DATA_STRING}.tar


umount kmre-filesystem
umount ${TMPDIR}/squashfs-root 2>/dev/null
rm -rf ${TMPDIR}/squashfs-root
